package cn.ubeta.b2c.navigation;

import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.view.SimpleDraweeView;
import cn.ubeta.b2c.DemoData;
import cn.ubeta.b2c.R;
import cn.ubeta.b2c.api.ApiCart;
import cn.ubeta.b2c.bean.CartCheckProductInfo;
import cn.ubeta.b2c.bean.CartInfo;
import cn.ubeta.b2c.bean.CartInfo.CartProductInfo;
import cn.ubeta.b2c.cart.CheckoutActivity;
import cn.ubeta.b2c.common.ListFragment;
import cn.ubeta.b2c.common.ListFragmentConfig;
import cn.ubeta.b2c.product.ProductDetail;
import cn.ubeta.b2c.utils.NetworkCallback;
import cn.ubeta.b2c.widget.recyclerview.BaseViewHolder;

import java.io.IOException;
import java.util.List;

import static android.graphics.drawable.Drawable.createFromStream;

/**
 * Created by denny on 16/8/17.
 */

public class CartFragment extends ListFragment<CartProductInfo> {

    private TextView mTvPrice;
    private TextView mTvPriceOrg;
    private TextView mTvCheckout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cart, container, false);
        mTvPrice = (TextView) view.findViewById(R.id.tv_price);
        mTvPriceOrg = (TextView) view.findViewById(R.id.tv_price_org);
        mTvCheckout = (TextView) view.findViewById(R.id.tv_checkout);
        mTvCheckout.setOnClickListener(v -> gotoCheckout());
        return view;
    }

    @Override
    protected ListFragmentConfig getConfig() {
        return new ListFragmentConfig(R.layout.item_cart);
    }

    @Override
    protected void bindItemView(BaseViewHolder helper, CartProductInfo productInfo) {
        // 商品图片
        String url = productInfo.getImgUrl();
        SimpleDraweeView img = helper.getView(R.id.iv_product);
        img.setOnClickListener(v -> ProductDetail.gotoDetail(getContext(), productInfo));
        if (!TextUtils.isEmpty(url)) {
            img.setImageURI(Uri.parse(url));
        }
        // TODO 待删除
        Drawable d = null;
        try {
            d = createFromStream(getContext().getAssets().open(productInfo.getSkuId() + ".jpg"), null);
        } catch (IOException e) {
        }
        img.setImageDrawable(d);
        if (d == null) {
            GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(getResources());
            GenericDraweeHierarchy hierarchy = builder
                    .setFadeDuration(300)
                    .setPlaceholderImage(R.drawable.placeholder_small)
                    .build();
            img.setHierarchy(hierarchy);
        }

        // 商品标题
        String name = productInfo.getName();
        if (!TextUtils.isEmpty(name)) {
            ((TextView) helper.getView(R.id.tv_name)).setText(name);
        }
        // 商品价格
        ((TextView) helper.getView(R.id.tv_price)).setText("￥" + productInfo.getPriceInfo().getPrice() + ".00");
        // 商品数量
        ((TextView) helper.getView(R.id.tv_count)).setText(productInfo.getCount() + "件");

        // 长按删除
        helper.getConvertView().setOnLongClickListener(v -> conformRemove(productInfo.getSkuId()));

        // 勾选
        CheckBox cb = helper.getView(R.id.cb_cart);
        cb.setChecked(productInfo.isChecked());
        cb.setOnCheckedChangeListener((buttonView, isChecked) -> checkProduct(productInfo.getSkuId(), isChecked));
    }

    /**
     * 勾选商品
     * @param skuId
     * @param checked
     */
    private void checkProduct(long skuId, boolean checked) {
        ApiCart.cartCheckProduct(skuId, checked, new NetworkCallback<CartCheckProductInfo>() {
            @Override
            public void onResponse(CartCheckProductInfo result) {
                List<CartProductInfo> list = DemoData.getCartInfo().getProductList();
                for (CartProductInfo info : list) {
                    if (info.getSkuId() == result.getSkuId()) {
                        info.setChecked(result.isChecked());
                        DemoData.putCartInfo();
                        updateCheckoutBtn();
                        break;
                    }
                }
                loadNew();
            }

            @Override
            public void onFailure(IOException e) {

            }
        });
    }

    /**
     * 确认是否删除
     */
    private boolean conformRemove(long skuId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("确认删除吗?");
        builder.setPositiveButton("确定", (dialog, which) -> {
            for (int i = 0; i < mAdapter.getItemCount(); ++i) {
                if (((CartProductInfo)mAdapter.getItem(i)).getSkuId() == skuId) {
                    DemoData.remove(skuId);
                    mAdapter.notifyDataSetChanged();
                    List<CartProductInfo> list = DemoData.getCartInfo().getProductList();
                    computePrice(list);
                    updateCheckoutBtn();
                    break;
                }
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
        return true;
    }

    @Override
    protected void onLoadFinish(boolean respOk) {
        CartInfo info = DemoData.getCartInfo();
        if (info == null)
            return;
        List<CartProductInfo> list = info.getProductList();
        computePrice(list);
        updateCheckoutBtn();
    }

    /**
     * 更新结算按钮状态
     */
    private void updateCheckoutBtn() {
        CartInfo info = DemoData.getCartInfo();
        if (info == null) {
            mTvCheckout.setEnabled(false);
            return;
        }

        List<CartProductInfo> list = info.getProductList();
        if (list != null && list.size() > 0) {
            for (CartProductInfo item : list) {
                if (item.isChecked()) {
                    mTvCheckout.setEnabled(true);
                    return;
                }
            }
        }
        mTvCheckout.setEnabled(false);
    }

    /**
     * 计算价格
     * @param list
     */
    private void computePrice(List<CartProductInfo> list) {
        int total = 0;
        if (list != null) {
            for (CartProductInfo item : list) {
                total += (item.getCount() * item.getPriceInfo().getPrice());
            }
        }
        mTvPrice.setText("支付：" + total + ".00");
        mTvPriceOrg.setText("原价：" + total + ".00");
    }

    @Override
    protected void loadData(int page) {
        ApiCart.getCartProductList(getNetworkCallback());
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // onResume / onPause
        if (isVisibleToUser) {
            loadNew(true);
        }
    }

    /**
     * 去结算
     */
    private void gotoCheckout() {
        CheckoutActivity.gotoActivity(getContext(), CheckoutActivity.class);
        getActivity().overridePendingTransition(R.anim.in_right_to_left, android.R.anim.fade_out);
    }

    /**
     * 获取实例
     */
    public static CartFragment newInstance() {
        return new CartFragment();
    }
}
